<?php
namespace Home\Controller;
use Think\Controller;

class FrontController extends Controller {
	protected function _initialize() {
		//===系统信息======
		$system = D('System')->find(1);
		$this->assign('system', $system);
        //如果微信已登录，但是没有绑定手机号，提示
        if ((session('用户')) && (!session('用户')['username']) && (CONTROLLER_NAME != 'User') && (ACTION_NAME != 'detail')) {
        	// $_SESSION['lastFundingTo'] = true; //用于支持微信用户没绑手机号情况下的跳转
            $this->success('请先填写手机号码!', U('User/detail'));
        }
	}
	public function isWeixin(){ 
		if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
				return true;
		}
		return false;
	}


	/**
	 * 典型detail操作
	 * 无任何定制化需求的model可以直接服用本action
	 */
	public function detail($id = 0) {
		$model = D(CONTROLLER_NAME);
		$detail = $model->find($id);
		$this->assign('detail', $detail);
		$this->display('detail');
	}

	/**
	 * 典型list操作
	 * 无任何定制化需求的model可以直接服用本action
	 */
	public function list() {
		$this->page();
		$this->display();
	}

	/**
	 * 分页数据渲染
	 * @params array $searchMap 寻找元素时的条件,默认为$_GET['searchMap']的值
	 */
	public function page() {
		$searchMap = $this->handleSearchMap($_GET["searchMap"]);
		$model = D(CONTROLLER_NAME);
		$count = $model->where($searchMap)->count();
		$page = new \Think\SuiPage($count, C('PAGE_NUM'));
		$show = $page->show();
		$list = $model->where($searchMap)->order('id desc')->limit($page->firstRow . ',' . $page->listRows)->select();
		$this->assign('list', $list);
		$this->assign('page', $show);
	}

	/**
	 * 典型create操作
	 * 无任何定制化需求的model可以直接复用本action
	 */
	public function create($param = []) {
		if (IS_POST) {
			$model = D(CONTROLLER_NAME);
			if (count($_FILES) !== 0) {
				$upload = new \Think\Upload(); // 实例化上传类
				$upload->maxSize = 99999999; // 设置附件上传大小
				$upload->rootPath = './Public/file/'; // 设置附件上传根目录
				$upload->savePath = ''; // 设置附件上传（子）目录
				$upload->autoSub = false;
				$info = $upload->upload();
				if (!$info) {
// 上传错误提示错误信息
					$this->error($upload->getError());
					return false;
				}
				foreach ($_FILES as $field => $file) {
					$_POST[$field] = $info[$field]['savename'];
				}
			}
			if (!$model->create()) {
				$this->error($model->getError());
				return false;
			}
			$newId = $model->add();
			$this->interfaceAfterCreate($newId);
			if (!$param['redirect']) {
				$this->success('新增成功!', U('list'));
			} else {
				$this->success('新增成功!', $param['redirect']);
			}
		}
		$this->display('update');
	}

	/**
	 * 典型delete操作
	 * 无任何定制化需求的model可以直接服用本action
	 */
	public function delete($id = 0, $param = []) {
			$this->interfaceBeforeDelete($id);
			$model = D(CONTROLLER_NAME);
			//删除文件
			// foreach ($model->fieldMap as $field => $param) {
			// 	if ($param['type'] === 'file') {
			// 		$deleteModels = $model->select($id);
			// 		foreach ($deleteModels as $deleteModel) {
			// 			unlink('./Public/file/' . $deleteModel[$field]);
			// 		}
			// 	}
			// }
			$model->delete($id);
			if (!$param['redirect']) {
				$this->success('删除成功!', U('list'));
			} else {
				$this->success('删除成功!', $param['redirect']);
			}
	}

	/**
	 * 典型update操作
	 * 无任何定制化需求的model可以直接服用本action
	 */
	public function update($id = 0, $param = []) {
		$model = D(CONTROLLER_NAME);
		if (IS_POST) {
			$this->interfaceBeforeUpdate($id);
			$_POST['id'] = $id;
			if (count($_FILES) !== 0) {
				$upload = new \Think\Upload(); // 实例化上传类
				$upload->maxSize = 99999999; // 设置附件上传大小
				$upload->rootPath = './Public/file/'; // 设置附件上传根目录
				$upload->savePath = ''; // 设置附件上传（子）目录
				$upload->autoSub = false;
				$info = $upload->upload();
				if ($info) {
					//上传成功，删除原有文件
					foreach ($_FILES as $field => $file) {
						$_POST[$field] = $info[$field]['savename'];
						if ($info[$field]['savename']) {
							if (isset($id)) {
								$modelTemp = $model->find($id);
								unlink('./Public/file/' . $modelTemp[$field]);
							}
						}
					}
				} else {
					// 上传错误提示错误信息
					//$this->error($upload->getError());
					//return false;
				}

			}
			if (!$model->create()) {
				$this->error($model->getError());
				return false;
			}
			$model->save();
			if (method_exists($this, 'interfaceAfterUpdate')) {
				$this->interfaceAfterUpdate($id);
			}
			if (!$param['redirect']) {
				$this->success('修改成功!', U('list'));
			} else {
				$this->success('修改成功!', $param['redirect']);
			}

		}
		$modelData = $model->getById($id);
		if (!$modelData) {
			$this->error('非法操作!');
			return false;
		}
		$this->assign('model', $modelData);
		$this->display();
	}

	/**
	 * 对searchMap中需要特殊处理的值进行处理
	 * @params $searchMap : 待处理的searchMap
	 * @return $searchMap : 处理完成的searchMap
	 */
	public function handleSearchMap($searchMap = '') {
		$searchMap = array_filter($searchMap);
		$model = D(CONTROLLER_NAME);
		//时间筛选需特殊处理
		foreach ($searchMap as $field => $value) {
			if (strstr($field, 'Start')) {
				$startField = $field;
				$endField = str_replace("Start", "End", $field);
				$field = str_replace('Start', '', $field); //此后的field为真实field
				$startTime = $searchMap[$startField];
				$endTime = $searchMap[$endField];
				unset($searchMap[$startField]);
				unset($searchMap[$endField]);
				$searchMap[$field] = ['between', [strtotime($startTime), strtotime($endTime)]];
			}
			$param = $model->fieldMap[$field];
			if (($param['type'] == 'foreign') && (explode(',', $param['content'])[3] == 'input')) {
				if ($searchMap[$field]) {
					$foreignArr = explode(',', $param['content']);
					$retArr = D(ucfirst($foreignArr[0]))->where([$foreignArr[2] => $searchMap[$field]])->select();
					$retStr = '';
					foreach ($retArr as $key => $value) {
						$retStr .= $value[$foreignArr[1]] . ',';
					}
					$retStr = rtrim($retStr, ",");
					$searchMap[$field] = ['IN', $retStr];
				}
			}
		}
		return $searchMap;
	}

	public function interfaceAfterCreate() {
	}
	public function interfaceBeforeUpdate() {
	}
	public function interfaceBeforeDelete() {
	}


}
